//
//  UserModel.m
//  WorkNest
//
//  Created by qbm360 on 15/7/6.
//  Copyright (c) 2015年 nest. All rights reserved.
//

#import "UserModel.h"

@implementation UserModel

@synthesize userName = _userName;
@synthesize password = _password;
@synthesize userData = _userData;
@synthesize userToken = _userToken;

static dispatch_once_t onceToken;

+ (instancetype)modelObjectWithDictionary:(NSDictionary *)dict {
    return [[self alloc] initWithDictionary:dict];
}

- (instancetype)initWithDictionary:(NSDictionary *)dict {
    self = (dict && [dict isKindOfClass:[NSDictionary class]]) ? [super init] : nil;
    if(self && [dict count]) {
        self.userName = [dict valueForKey:@"userName"];
        self.password = [dict valueForKey:@"password"];
        self.userToken = [dict valueForKey:@"userToken"];
    }
    
    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        self.userName = [aDecoder decodeObjectForKey:@"userName"];
        self.password = [aDecoder decodeObjectForKey:@"password"];
        self.userToken = [aDecoder decodeObjectForKey:@"userToken"];
    }
    return self;
}

-(void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:_userToken forKey:@"userToken"];
    [aCoder encodeObject:_userName forKey:@"userName"];
    [aCoder encodeObject:_password forKey:@"password"];    
}

+ (instancetype)sharedInstance {
    static UserModel *_sharedInstance = nil;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [UserModel new];
        _sharedInstance.userToken = DEFAULTS(object, @"userToken");
        _sharedInstance.userName = DEFAULTS(object, @"userName");
//        _sharedInstance.userData = [UIUtil unarchiveDataFromDefaultsWithKey:@"userData"];
    });
    return _sharedInstance;
}

+ (void)resetSharedClient {
    onceToken = 0;
}

//- (void)setUserData:(UserModel *)userData
//{
//    _userData = userData;
//    if (!_userData) {
//        [UIUtil removeArchivedDataWithKey:@"userData"];
//    } else {
//        [UIUtil archiveDataToDefaults:_userData withKey:@"userData"];
//    }
//}

- (void)setUserToken:(NSString *)userToken
{
    _userToken = userToken;
    if (!_userToken || [_userToken isEqualToString:@""]) {
        RM_DEFAULTS(@"userToken");
    } else {
        SET_DEFAULTS(Object, @"userToken", _userToken);
    }
}

- (void)setUserName:(NSString *)userName
{
    _userName = userName;
    if (!_userName || [_userName isEqualToString:@""]) {
        RM_DEFAULTS(@"userName");
    } else {
        SET_DEFAULTS(Object, @"userName", _userName);
    }
}

@end
